package com.execute;

import com.common.protobuf.MessageBuilder;
import com.common.protobuf.MessageModule;
import com.common.protobuf.Result;
import com.scanner.Invoker;
import com.scanner.InvokerTable;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author 顾志杰
 * @date 2021/3/16-14:04
 */
public class MessageTask4Request implements Runnable{

    private MessageModule.Message message;

    private ChannelHandlerContext ctx;

    private static final String RETURN = "-return";

    public MessageTask4Request(MessageModule.Message message, ChannelHandlerContext ctx){
        this.message = message;
        this.ctx = ctx;
    }

    @Override
    public void run() {
        String module = message.getModule();
        String cmd = message.getCmd();
        byte[] data = message.getBody().toByteArray();
        Invoker invoker = InvokerTable.getInvoker(module, cmd);
        assert invoker != null;
        Result<?> result = (Result<?>) invoker.invoke(data);
        ctx.writeAndFlush(MessageBuilder.getResponseMessage(
                module + RETURN,
                cmd + RETURN,
                result.getResultType(),
                result.getContent()));

    }
}
